import config from '../config/index.js'

class Http {
	constructor(config) {
		this.config = config
	}

	request(opt) {
		return new Promise((resolve, reject) => {
			const {
				url,
				data,
				dataType,
				method,
				header,
				timeout
			} = this.handleOpt(opt)
			if (opt.loading) {
				uni.showLoading()
			}
			const requestTask = uni.request({
				url: url,
				data: data,
				dataType: dataType,
				method: method,
				header: header,
				timeout: timeout,
				success: (res) => {
					if (opt.loading) {
						uni.hideLoading()
					}
					const bussinessCode = res.data[this.config.bussinessCodeKey]
					// 异常处理
					if (this.config.successCode != bussinessCode) {
						// 回调
						if (this.config.errCallBack[bussinessCode]) {
							this.config.errCallBack[bussinessCode]()
						} else {
							// console.log(res);
							// 提示
							uni.showToast({
								title: res.data[this.config.msgKey] || res.data.data,
								duration: 2000,
								mask: false,
								icon: 'none'
							});
						}
						resolve(false)
					} else {
						resolve(res.data)
					}
				},
				fail: (err) => {
					if (opt.loading) {
						uni.hideLoading()
					}
					reject(err)
				}
			})
		})
	}

	handleOpt(opt) {
		const map = {
			url: opt.fullUrl || this.config.baseUrl + opt.url,
			data: opt.data || {},
			dataType: opt.dataType || this.config.dataType,
			method: opt.method || this.config.defaultMethod,
			header: opt.header || {
				'content-type': this.config.contentType,
				[this.config.tokenKeyName]: uni.getStorageSync('token') || null,
			},
			timeout: this.config.timeout
		}
		if (opt.noToken) {
			delete map.header[this.config.tokenKeyName]
		}
		return map
	}
}

const http = new Http(config)

export default http